/**
 * jqGrid插件封装；设置一些默认的参数
 */
+function($){
	
	var JQGridUtils = function (element,options) {
		this.element = element;
		this.initOptions(options);
		this.execute();
	};
	/**
	 * 默认参数
	 */
	JQGridUtils.defaultOptions = {
			autowidth: false,
			viewrecords: true
	};
	JQGridUtils.ROW_HEIGHT = 36;
	JQGridUtils.HEADER_HEIGHT = 37;
	JQGridUtils.FOOTER_HEIGHT = 40;
	
	JQGridUtils.prototype = {
			constructor: JQGridUtils,
			/**
			 * 初始化参数
			 * @param options
			 * @returns {JQGridUtils}
			 */
			initOptions : function(options) {
				this.options = $.extend(true,JQGridUtils.defaultOptions,options);
				return this;
			},
			/**
			 * 执行
			 */
			execute : function() {
				$.jgrid.defaults.styleUI = 'Bootstrap';
				$.jgrid.styleUI.Bootstrap.base.rowTable = "table table-bordered table-striped";
				var isAutoHeight = false;
				var isAutoWidth = false;
				var isSearchPanel = false;
				if(utils.isEmpty(this.options.height) || this.options.height == 0) {
					var searchH = 0;
					if(this.options.toolbar && this.options.toolbar[2]) {
						searchH = $(this.options.toolbar[2]).outerHeight() + 5;
					}
					this.options.height = this.autoHeight() - searchH;
					isAutoHeight = true;
				}
				if(utils.isEmpty(this.options.width) || this.options.width == 0) {
					this.options.width=$(window).width() - 5;
					isAutoWidth = true;
				}
				if(this.options.toolbar)
					isSearchPanel = true;
				this.element.jqGrid(this.options);
				$("#gbox_"+this.element.attr("id")).attr("autoheight",isAutoHeight).attr("autowidth",isAutoWidth).attr("searchpanel",isSearchPanel);
			},
			/**
			 * 高度自适应
			 */
			autoHeight : function() {
				var h = $(window).height() - this.getNotTableHeight() - 4;
				if(utils.isNotEmpty(this.options.offset)) {
					h = h - this.options.offset;
				}
				return h;
			},
			/**
			 * 设置jqGrid高度
			 * @param h
			 */
			setHeight : function(h) { 
				h = h - this.getNotTableHeight();
				this.element.jqGrid('setGridHeight', h);
			},
			/**
			 * 获取不是表格内容的高度；如：标题，表格头，表格尾，工具栏等的高度
			 * @returns {Number}
			 */
			getNotTableHeight: function() {
				var jqGridH = 0;
				if(utils.isEmpty(this.options.caption)) {
					jqGridH = JQGridUtils.HEADER_HEIGHT + JQGridUtils.FOOTER_HEIGHT;
				} else {
					jqGridH = JQGridUtils.HEADER_HEIGHT * 2 + JQGridUtils.FOOTER_HEIGHT;
				} 
				if(this.options.toolbar) {
					//var searchH = $(this.options.toolbar[2]).height()/3;
					//console.log(searchH);
					jqGridH += 4;
				}
				return jqGridH;
			}
	};
	
	$.fn.jqGridUtils = function(options) {
		var $this = $(this);
		var jqGrid = $this.data("mix.jqgrid");
		if(!jqGrid) {
			jqGrid = new JQGridUtils($this, options);
			$this.data("mix.jqgrid",jqGrid);
		}
		return jqGrid;
	}
	
}(jQuery)